package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"house-property/common"
	"house-property/model"
	"log"
)
func Login(ctx *gin.Context){
	DB:=common.InitDB()
	b, _ := ctx.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	name := m["name"]
	num := m["num"]
	//log.Println(username)
	//log.Println(password)
	//name := ctx.PostForm("name")
	//num:=ctx.PostForm("num")
	//if len(num) != 11 {
	//	ctx.JSON(200, gin.H{
	//		"code":  3000,
	//		"msg":   "手机号必须为11位",
	//		"weqie": len(num),
	//	})
	//	return
	//}
	if len(name) == 0 {
		ctx.JSON(200, gin.H{
			"code": 3001,
			"msg":  "名字不能为空",
		})
		return
	}
	if !isTelephoneExist(DB,num){
		ctx.JSON(200,gin.H{
			"code":3002,
			"msg":"账号不存在，请先注册",
		})
		return
	}
	if !istelematchingname(DB,num,name){
		ctx.JSON(200,gin.H{
			"code":3003,
			"msg":"名字或者密码输入错误",
		})
		return
	}
     	ctx.JSON(200,gin.H{
     		"code":200,
     		"msg":"登陆成功",
		})
}
func istelematchingname(db *gorm.DB,num string,name string)bool{
	var user model.Register_im
	db.Where("NUM=?",num).First(&user)
	db.Where("NAME=?",name).First(&user)
	if user.Unum!=num||user.Name!=name{
		return true
	}
	return false
}
func isTelephoneExist(db *gorm.DB,telephone string)bool{
	var user model.Register_im
	db.Where("NUM=?",telephone).First(&user)
	log.Println(user)
	if user.Unum!=""{
		return true
	}
	return false
}
